/*
 * @(#)HttpTest.java	1.32 01/05/07
 * Copyright (c) 2004 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

package example.http;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import java.lang.String;

/**
 * An example MIDlet to fetch a page using an HttpConnection.
 * Refer to the startApp, pauseApp, and destroyApp
 * methods so see how it handles each requested transition.
 *
 * Note: if you run this inside POSE using a multi-homed PC (with more
 * than one network connections), POSE doesn't know how to resolve
 * host names not connected to the first network card. To solve this,
 * add a line like this in your c:/WINNT/system32/drivers/etc/hosts
 * file:
 *
 * 204.71.202.160  www.yahoo.com
 */
public class HttpTest extends MIDlet implements CommandListener {
    /** User interface command to exit the current application. */
    private Command exitCommand  = new Command("Exit", Command.EXIT, 2);
    /** User interface command to issue an HTTP GET request. */
    private Command getCommand = new Command("Get", Command.SCREEN, 1);
    /** User interface command to issue an HTTP POST request. */
    private Command postCommand = new Command("Post", Command.SCREEN, 1);
    /** User interface command to issue an HTTP HEAD request. */
    private Command headCommand = new Command("Head", Command.SCREEN, 1);
    /** User interface command to choose a test. */
    private Command chooseCommand = new Command("Choose", Command.SCREEN, 2);
    /** User interface command to Add a new location. */
    private Command addCommand = new Command("Add", Command.SCREEN, 1);
    /** User interface command to confirm current operation. */
    private Command okCommand = new Command("OK", Command.OK, 1);
    /** User interface command to abort current operation. */
    private Command cancelCommand = new Command("Cancel", Command.CANCEL, 1);

    /** The current display object. */
    private Display display;
    /** The url to GET from the network. */
    private String url;
    /** Array of target locations. */
    Vector urls;
    /** User interface list for selection. */
    List list;
    /** Message area for user entered URl. */
    TextBox addTextBox;

    /** Initialize the MIDlet with a handle to the current display */
    public HttpTest() {
        urls = new Vector();
        urls.addElement("http://www.yahoo.com/");
        urls.addElement("http://www.sun.com/");
        urls.addElement("https://central.sun.net/");
        urls.addElement("https://www.wellsfargo.com");
        urls.addElement("-----------------------");
        urls.addElement("http://jse.east/Telco/HttpTest.txt");
        urls.addElement("http://spiro.eng/");
        urls.addElement("http://spiro.eng:80/");
        urls.addElement("http://localhost:8080/");
        urls.addElement("-----------------------");
        urls.addElement("http://mal\\formed:axyt/url???");
        urls.addElement("http://www.yahoo.com/no/such/page/");
        urls.addElement("http://www.yahoo.com:29999/no/such/port/");
        urls.addElement("http://no.such.site/");
        urls.addElement("http://www.yahoo.com/bad_proxy/");

        url = (String)urls.elementAt(0);
	display = Display.getDisplay(this);
    }
    /** Current attempt count. */
    int attempt = 0;

    /**
     * Debug output routine.
     * @param s string to be printed.
     */
    static final void DEBUG(String s) {
        if (true) {
            System.out.println(s);
        }
    }

    /**
     * Start creates the thread to do the timing.
     * It should return immediately to keep the dispatcher
     * from hanging.
     */
    public void startApp() {
	// Use the specified URL is overriden in the descriptor
	String u = getAppProperty("HttpTest-Url");
	if (u != null) {
	    url = u;
	}
	    
	mainScreen();
    }
    /**
     * Display the main screen.
     */
    void mainScreen() {
        String s = "URL = " + url +
            ". Press Get or Post to fetch it, or Choose to " +
            "use another URL";
        TextBox t = new TextBox("Http Test", s, s.length(), 0);
        setCommands(t, false);
	display.setCurrent(t);
    }
    /**
     * Pick a screen.
     */
    void chooseScreen() {
        list = new List("Choose URL", Choice.EXCLUSIVE);
        for (int i = 0; i < urls.size(); i++) {
            list.append((String)urls.elementAt(i), null);
        }
        setCommands(list, true);
	display.setCurrent(list);
    }
    /**
     * Add another screen.
     */
    void addScreen() {
        addTextBox = new TextBox("New URL", "http://", 200, 0);
        addTextBox.addCommand(okCommand);
        addTextBox.addCommand(cancelCommand);
        addTextBox.setCommandListener(this);
	display.setCurrent(addTextBox);
    }
    /**
     * Read the content of the page. Don't care about the response
     * headers.
     * @param request type of HTTP request (GET or POST)
     */
    private void readContents(String request) {
	StringBuffer b = new StringBuffer();
        ++ attempt;
        b.append("attempt " + attempt + " content of " 
                 + request + " " + url + "\n");
	StreamConnection c = null;
        InputStream is = null;
	TextBox t = null;
	try {
	    long len = -1;
	    int ch = 0;
            long count = 0;

            DEBUG("Read Page: " + url); 
            c = (StreamConnection)Connector.open(url);
            DEBUG("c= " + c);
	    is = c.openInputStream();

            DEBUG("is = " + is);
            if (c instanceof HttpConnection) {
                len = ((HttpConnection)c).getLength();
            }
            DEBUG("len = " + len);
	    if (len != -1) {
		// Read exactly Content-Length bytes
                DEBUG("Content-Length: " + len);

		for (int i = 0; i < len; i++) {
		    if ((ch = is.read()) != -1) {
			if (ch <= ' ') {
                            ch = ' ';
                        }
			b.append((char) ch);
                        count ++;
                        if (count > 200) {
                            break;
                        }
		    }
                }
	    } else {
                byte data[] = new byte[100];
                int n = is.read(data, 0, data.length);
                for (int i = 0; i < n; i++) {
                    ch = data[i] & 0x000000ff;
		    b.append((char)ch);
		}
	    }
	    try {
                if (is != null) {
                    is.close();
                }
                if (c != null) {
                    c.close();
                }
	    } catch (Exception ce) {
		DEBUG("Error closing connection");
	    }

	    try {
		len = is.available();
		DEBUG("Inputstream failed to throw IOException after close");
	    } catch (IOException io) {
                DEBUG("expected IOException (available())");
                io.printStackTrace();
		// Test to make sure available() is only valid while
		// the connection is still open.,
	    }

	    t = new TextBox("Http Test", b.toString(), b.length(), 0);
            is = null;
            c = null;
	} catch (IOException ex) {
            ex.printStackTrace();
            DEBUG(ex.getClass().toString());
            DEBUG(ex.toString());
	    DEBUG("Exception reading from http");
	    if (c != null) {
		try {
		    String s = null;
                    if (c instanceof HttpConnection) {
                        s = ((HttpConnection)c).getResponseMessage();
                    }
		    DEBUG(s);
		    if (s == null)
			s = "No Response message";
		    t = new TextBox("Http Error", s, s.length(), 0);
		} catch (IOException e) {
		    e.printStackTrace();
		    String s = e.toString();
		    DEBUG(s);
		    if (s == null)
			s = ex.getClass().getName();
		    t = new TextBox("Http Error", s, s.length(), 0);
		}
	    } else {
		t = new TextBox("Http Error", "Could not open URL", 128, 0);
	    }
	} catch (IllegalArgumentException ille) {
	    // Check if an invalid proxy web server was detected.
	    t  = new TextBox("Illegal Argument",  
                             "Check the com.sun.midp.io.http.proxy setting.",
                             128, 0);
	}

        if (is != null) {
	    try {
		is.close();
	    } catch (Exception ce) {; }
        }
        if (c != null) {
	    try {
		c.close();
	    } catch (Exception ce) {; }
        }

        setCommands(t, false);
	display.setCurrent(t);
    }

    /**
     * Read the header of an HTTP connection. Don't care about
     * the actual data.
     *
     * All response header fields are displayed in a TextBox screen. 
     * @param request type of HTTP request (GET or POST)
     */
    private void readHeaders(String request) {
	StringBuffer b = new StringBuffer();

	try {
	    HttpConnection c = null;
	    c = (HttpConnection)Connector.open(url);
	    c.setRequestMethod(request);
	    
	    b.append("URL: " + c.getURL() +
		"\nProtocol: " + c.getProtocol() +
		"\nHost: " + c.getHost() +
		"\nFile: " + c.getFile() +
		"\nRef: " + c.getRef() +
		"\nQuery: " + c.getQuery() +
		"\nPort: " + c.getPort() +
		"\nMethod: " + c.getRequestMethod());
	    InputStream is = c.openInputStream();

            // DEBUG: request DEBUG(b) ; 

	    b.append("\nResponseCode: " + c.getResponseCode() +
                     "\nResponseMessage:" + c.getResponseMessage() + 
                     "\nContentLength: " + c.getLength() +
                     "\nContentType: " + c.getType() +
                     "\nContentEncoding: " + c.getEncoding() +
                     "\nContentExpiration: " + c.getExpiration() +
                     "\nDate: " + c.getDate() +
                     "\nLast-Modified: " + c.getLastModified() + "\n\n");

            // DEBUG: Reply  DEBUG(b) ; 

	    int h = 0;
	    while (true) {
		try {
		    String key = c.getHeaderFieldKey(h);
		    if (key == null) 
			break;
		    String value = c.getHeaderField(h);
		    b.append(key + ": " + value + "\n");
		    h++;
                    // DEBUG: DEBUG( key + "(" + h + "): " +
                    //        value) ;
		}
		catch (Exception e) {
		    // DEBUG: DEBUG(
                    //     "Exception while fetching headers");
		    break;
		}
	    }
	    try {
		is.close();
		c.close();
	    } catch (Exception ce) {
		// DEBUG: DEBUG("Error closing connection");
	    }

	    TextBox t = new TextBox("Http Test", b.toString(), b.length(), 0);
	    // DEBUG:	    DEBUG (b.toString());

            setCommands(t, false);
	    display.setCurrent(t);
	} catch (IOException ex) {
            ex.printStackTrace();
	}
    }
    /**
     * Set the funtion to perform based on commands selected.
     * @param d Displaybale object 
     * @param islist flag to indicate list processing
     */
    void setCommands(Displayable d, boolean islist) {
        if (islist) {
            d.addCommand(addCommand);
            d.addCommand(okCommand);
        } else {
            d.addCommand(exitCommand);
            d.addCommand(chooseCommand);
            d.addCommand(getCommand);
            d.addCommand(postCommand);
            d.addCommand(headCommand);
        }
        d.setCommandListener(this);
    }

    /**
     * Pause signals the thread to stop by clearing the thread field.
     * If stopped before done with the iterations it will
     * be restarted from scratch later.
     */
    public void pauseApp() {
    }

    /**
     * Destroy must cleanup everything.  The thread is signaled
     * to stop and no result is produced.
     * @param unconditional Flag to indicate that forced shutdown
     * is requested
     */
    public void destroyApp(boolean unconditional) {
    }

    /**
     * Respond to commands, including exit
     * @param c command to perform
     * @param s Screen displayable object
     */
    public void commandAction(Command c, Displayable s) {
	if (c == exitCommand) {
	    destroyApp(false);
	    notifyDestroyed();
	} else if (c == getCommand) {
	    readContents(HttpConnection.GET);
	} else if (c == postCommand) {
	    readContents(HttpConnection.POST);
	} else if (c == headCommand) {
	    readHeaders(HttpConnection.HEAD);
	} else if (c == chooseCommand) {
            chooseScreen();
	} else if (c == okCommand) {
            if (s == list) {
                int i = list.getSelectedIndex();
                if (i >= 0) {
                    url = list.getString(i);
                }
                mainScreen();
            } else if (s == addTextBox) {
                urls.addElement(addTextBox.getString().trim());
                chooseScreen();
            }
	} else if (c == addCommand) {
            addScreen();
	} else if (c == cancelCommand) {
            chooseScreen();
	}
    }
}

